#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <string.h>

void mywrite(int wfd)
{
  char message[1024] = {0};
  int i = 15;
  while(1)
  {

    snprintf(message, sizeof(message), "send a message to father, mypid is : %d, i = %d\n", getpid(), i);
    --i;
    write(wfd, message, strlen(message));
    sleep(1);

  }
}

void myread(int rfd)
{
  char message[1024] = {0};
  
  while(1)
  {
    ssize_t n = read(rfd, message, sizeof(message)-1);
    message[n] = '\0';
    printf("%s", message);
    sleep(1);
  }

}



int main()
{
 //子进程写，父进程读
 int pipefd[2] = {0};
 int pret = pipe(pipefd);
 if(pret)
 {
   perror("管道创建失败\n");
   return 0;
 }
 int id = fork();
 if(id == 0)
 {
  close(pipefd[0]);
  mywrite(pipefd[1]);
  exit(0);

 }
 close(pipefd[1]);
 myread(pipefd[0]);
 wait(NULL);

 
  return 0;
}
